﻿/// <reference path="../../knockout-2.1.0.js" />
/// <reference path="../../knockout.mapping-latest.js" />
/// <reference path="../shared/utils.js" />
/// <reference path="../../jquery-1.9.1-vsdoc.js" />
/// <reference path="../../knockout.wrap.js" />
/// <reference path="../../thrid-party/knockout.validation.v0.9.js" />
var ignoredMapping = { ignore: ["TiposIdentificacion", "Generos", "GrupoSanguineos", "Medicos", "Estado"] };

function ExamenModel(data) {
    this.Id = ko.observable(data.Id);
    this.IdCita = ko.observable(data.IdCita);
    this.Tipo = ko.observable(data.Tipo);
    this.FechaCreacion = ko.observable(data.FechaCreacion);
}

function ExamenViewModel(idIndividuo) {
    var self = this;
    self.Examenes = ko.observableArray([]);
    $.getJSON("/Registro/ListaExamenes/" + idIndividuo, function (response) {
        if (response.lista)
            self.Examenes(response.lista);
    });
    self.PageSize = ko.observable(5);
    self.PageIndex = ko.observable(0);
    self.PreviousPage = function () { self.PageIndex(self.PageIndex() - 1); };
    self.NextPage = function () { self.PageIndex(self.PageIndex() + 1); };
    self.PagedRows = ko.dependentObservable(function () {
        var size = self.PageSize();
        var start = self.PageIndex() * size;
        return self.Examenes.slice(start, size + start);
    });
    self.MaxPageIndex = ko.dependentObservable(function () {
        return Math.ceil(self.Examenes().length / self.PageSize()) - 1;
    }); 
}

function IndividuoViewModel(data) {
    var self = this;
    self.Mensaje = ko.observable();
    self.HaveErrors = ko.observable(false);

    self.Save = function () {
        self.NoIdentificacion(self.NoIdentificacion().toString());
        ajax('Registro/Guardar', ko.mapping.toJSON(self, ignoredMapping), function (result) {
            if (result.isValid) {
                self.Mensaje("El individuo <b>" + self.Nombres() + " " + self.PrimerApellido() + "</b> fue registrado satisfactoriamente.");
                $('#modalsaved').modal();
                dispose();
            } else {
                self.HaveErrors(true);
                self.Mensaje(result.message);
            }
        });
    };
    self.ExamenesVM = ko.observable();
    self.Load = function (info) {
        ko.mapping.fromJS(info, {}, this);      
        if (info.IndividuoId) {
            self.ExamenesVM(new ExamenViewModel(info.IndividuoId));
        }
    };


    if (data)
        self.Load(data);

    function dispose() {
        self.HaveErrors(false);
    }
}

function BuscarUsuarioViewModel(data) {
    var self = this;
    self.Results = ko.observableArray([]);
    self.NoIdentificacionSearch = ko.observable('');
    self.Apellido = ko.observable('');

    /*Paging*/
    self.PageSize = ko.observable(25);
    self.PageIndex = ko.observable(0);
    self.PreviousPage = function () { self.PageIndex(self.PageIndex() - 1); };
    self.NextPage = function () { self.PageIndex(self.PageIndex() + 1); };
    self.MaxPageIndex = ko.computed(function () {
        return Math.ceil(self.Results().length / self.PageSize()) - 1;
    });
    self.PagedResults = ko.computed(function () {
        var size = self.PageSize();
        var start = self.PageIndex() * size;
        return self.Results.slice(start, size + start);
    });
    /*end Paging*/

    self.Mostar = function (selected) {
        location.hash = '/Editar?idIndividuo=' + selected.IndividuoId();
    };

    self.Buscar = function () {
        var ss = $.param({ id: self.NoIdentificacionSearch(), apellido: self.Apellido() });
        location.hash = "/Buscar?" + ss;
    };

    self.Load = function () {
        self.Results(ko.mapping.fromJS(data)());
    };

    if (data)
        self.Load(data);
}

function RegistroVM() {
    var self = this;
    self.Pages = ['Buscar', 'Crear'];
    self.CurrentPage = ko.observable();
    self.BuscarUsuario = ko.observable();
    self.IndividuoEditor = ko.observable();

    self.Load = function (data, page) {
        self.RefreshPages();
        self.CurrentPage(page);
        if (self.CurrentPage() == 'Crear')
            self.IndividuoEditor(new IndividuoViewModel(data.data, data.values));
        if (self.CurrentPage() == 'Buscar')
            self.BuscarUsuario(new BuscarUsuarioViewModel(data.data));
    };

    self.RefreshPages = function () {
        self.BuscarUsuario(null);
        self.IndividuoEditor(null);
    };

    var crear = {
        path: 'Crear',
        server: '/registro/FormJs',
        data: ko.observable({ page: "Crear" }),
        call: function (data) { self.Load(data, 'Crear'); }
    };
    var buscar = {
        path: 'Buscar',
        server: '/registro/ObtenerIndividuos',
        call: function (data) { self.Load(data, 'Buscar'); }
    };
    var editar = {
        path: 'Editar',
        server: '/registro/FormJs',
        data: ko.observable({ page: "Editar" }),
        call: function (data) { self.Load(data, 'Crear'); }
    };

    Routes([crear, buscar, editar]).run('/Registro#/Crear');
}

function startApp() {
    ko.applyBindings(new RegistroVM(), document.getElementById("RegistrosBox_binding"));
}

$(function () {
    startApp();
});